#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "encoder/encoder.h"
#include "buzzer/buzzer.h"
#include "sdcard/sdcard.h"
#include "dataprocess/json_builder.h"
#include "esp_mac.h"
#include "hal.h"

// 全局变量
int beep_fre = 600; // 初始频率
#define MIN_FREQUENCY 100  // 最低频率
#define MAX_FREQUENCY 5000 // 最高频率
static int packet_number = 1; // 数据包序号
QueueHandle_t hal_queue;      // 任务间队列

typedef struct {
    char mac[6];
    char mac_str[18];
    int direction;
    int button_state;
    int frequency;
} HalData;

// 按键和蜂鸣器任务
void button_buzzer_task(void *arg) {
    TickType_t last_wake_time = xTaskGetTickCount();
    while (1) {
        EncoderState *state = encoder_get_state();
        HalData data;

        // 获取 MAC 地址
        esp_base_mac_addr_get((uint8_t *)data.mac);

        // 判断方向
        switch (state->direction) {
            case ENCODER_ROTATE_FORWARD:
                data.direction = ENCODER_ROTATE_FORWARD;
                beep_fre += 100;
                if (beep_fre > MAX_FREQUENCY) beep_fre = MAX_FREQUENCY;
                break;
            case ENCODER_ROTATE_BACKWARD:
                data.direction = ENCODER_ROTATE_BACKWARD;
                beep_fre -= 100;
                if (beep_fre < MIN_FREQUENCY) beep_fre = MIN_FREQUENCY;
                break;
            case ENCODER_STILL:
                data.direction = ENCODER_STILL;
                break;
        }

        data.frequency = beep_fre;

        // 检测按键状态
        if (state->button == ENCODER_BUTTON_PRESSED) {
            data.button_state = ENCODER_BUTTON_PRESSED;

            // 蜂鸣器发声
            buzzer_set_frequency(beep_fre);
            buzzer_start();
            vTaskDelay(pdMS_TO_TICKS(50));
            buzzer_stop();
        } else if (state->button == ENCODER_BUTTON_RELEASED) {
            data.button_state = ENCODER_BUTTON_RELEASED;
        }

        // 将数据发送到队列
        if (xQueueSend(hal_queue, &data, pdMS_TO_TICKS(100)) != pdPASS) {
            printf("Failed to send data to queue\n");
        }

        vTaskDelayUntil(&last_wake_time, pdMS_TO_TICKS(500));
    }
}

// JSON 数据处理任务
void json_sdcard_task(void *arg) {
    const char *file_path = MOUNT_POINT"/data.txt";

    while (1) {
        HalData data;

        // 从队列中接收数据
        if (xQueueReceive(hal_queue, &data, portMAX_DELAY)) {
            snprintf(data.mac_str, sizeof(data.mac_str), "%02X:%02X:%02X:%02X:%02X:%02X", 
                data.mac[0], data.mac[1], data.mac[2], data.mac[3], data.mac[4], data.mac[5]);

            cJSON *json = json_builder_init(data.mac_str, packet_number++);
            if (!json) {
                printf("Failed to initialize JSON\n");
                continue;
            }

            // 添加 JSON 数据
            json_builder_add_string(json, "rotation",
                data.direction == ENCODER_ROTATE_FORWARD ? "forward" :
                data.direction == ENCODER_ROTATE_BACKWARD ? "backward" : "still");
            json_builder_add_int(json, "beep_frequency", data.frequency);
            json_builder_add_string(json, "button_state",
                data.button_state == ENCODER_BUTTON_PRESSED ? "pressed" : "released");

            // 转换为字符串并写入 SD 卡
            char *json_string = json_builder_to_string(json);
            if (json_string) {
                // 如果按键按下，则亲空当前txt文件中的数据
                if(data.button_state == ENCODER_BUTTON_PRESSED)
                {
                    esp_err_t ret = sdcard_write_file(file_path, "");
                    if (ret != ESP_OK) {
                    printf("Failed to clear SD data\n");
                    } else {
                        printf("success to clear SD data\n");
                    }
                }
                esp_err_t ret = sdcard_append_file(file_path, json_string);
                if (ret != ESP_OK) {
                    printf("Failed to append JSON to SD card\n");
                } else {
                    printf("Appended JSON to SD card: %s\n", json_string);
                }
                free(json_string);
            }

            // 清理 JSON 对象
            json_builder_cleanup(json);
        }
    }
}

// 初始化硬件和任务
void hal_init(void) {
    // 初始化编码器
    encoder_init(Encoder_A, Encoder_B, Encoder_K);

    // 初始化蜂鸣器
    buzzer_init(BUZZER_PIN);

    // 初始化 SD 卡
    esp_err_t ret = sdcard_init();
    if (ret != ESP_OK) {
        printf("Failed to initialize SD card during hal_init.\n");
    }

    // 创建任务间队列
    hal_queue = xQueueCreate(10, sizeof(HalData));
    if (hal_queue == NULL) {
        printf("Failed to create queue\n");
        return;
    }

    // 创建任务
    xTaskCreate(button_buzzer_task, "button_buzzer_task", 4096, NULL, 5, NULL);
    xTaskCreate(json_sdcard_task, "json_sdcard_task", 4096, NULL, 5, NULL);
}
